package com.zjun.pages;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页返回对象
 * 防腐层的一种实现
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PageResponse<T> implements Serializable {
    /**
     * 序列化版本
     */
    private static final long serialVersionUID = 1L;
    /**
     * 当前页
     */
    private Long current;
    /**
     * 每页大小
     */
    private Long size = 10L;
    /**
     * 总页数
     */
    private Long total;
    /**
     * 查询数据列表
     */
    private List<T> records = Collections.emptyList();
    public PageResponse(long current,long size){
        this(current,size,0);
    }
    public PageResponse(long current,long size,long total){
        if (current>1){
            this.current = current;
        }
        this.size = size;
        this.total = total;
    }
    public PageResponse setRecords(List<T> records){
        this.records = records;
        return this;
    }
    /**
     * 将数据列表的某个类转换成另一个类
     */
    public <R> PageResponse<R> covert(Function<?super T,?extends R> mapper){
        List<R> collect = this.records.stream().map(mapper).collect(Collectors.toList());
        return ((PageResponse<R>) this).setRecords(collect);
    }
}
